<template>
  <div
    ref="chat-room"
    class="app-container fix-navbar-overlay chat-room"
  >
    <NavBar>
      <template #left>
        <img
          @click="handleBackIconClick"
          src="/images/icon/back.svg"
          alt=""
        />
        <span>{{ receiverName || "清风" }} </span>
      </template>
      <template #right>
        <img
          @click="$router.push({ path: '/chat/chat-info' })"
          src="/images/icon/details.svg"
          alt=""
        />
      </template>
    </NavBar>

    <template v-if="!receiverName">
      <MsgAndUser
        :userUrl="'/images/mock/avator.png'"
        :isSelf="true"
        msg="阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿
            巴阿巴阿巴阿巴阿巴阿巴吧啦吧啦吧啦"
      />

      <MsgAndUser
        :userUrl="'/images/mock/avator.png'"
        :isSelf="true"
        msg="阿巴阿"
      />
      <MsgAndUser
        :userUrl="'/images/mock/avator.png'"
        msg="阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴吧啦吧啦吧啦"
      />
    </template>
    <MsgAndUser
      v-for="(msgAndUser, index) in msgAndUsers"
      :userUrl="'/images/mock/avator.png'"
      :isSelf="msgAndUser.isSelf"
      :msg="msgAndUser.msg"
      :key="msgAndUser.msg + index"
    />

    <div class="msg-action">
      <div class="icon-voice">
        <img src="images/icon/voice.svg" alt="" />
      </div>
      <input v-model="currentMsg" @keyup.enter="postMsg" />

      <template v-if="!currentMsg">
        <div class="icon-smile">
          <img src="images/icon/smile.svg" alt="" />
        </div>
        <img
          style="width: 25px"
          src="images/icon/plus.svg"
          alt=""
        />
      </template>
      <template v-else>
        <weui-button @click="postMsg" :mini="true">
          按钮
        </weui-button>
      </template>
    </div>
  </div>
</template>

<script>
import MsgAndUser from "src/views/chat/components/MsgAndUser.vue"
import NavBar from "src/components/NavBar.vue"
import { io } from "socket.io-client"

export default {
  components: {
    MsgAndUser,
    NavBar,
  },
  data: () => ({
    currentMsg: "",
    msgAndUsers: [],
    first: true,
  }),
  computed: {
    receiverName() {
      return this.$route.query.receiverName
    },
    receiverId() {
      return this.$route.query.recieverId
    },
  },
  watch: {
    async msgAndUsers() {
      await this.$nextTick()
      const { offsetHeight, scrollHeight, scrollTop } =
        this.$refs["chat-room"]
      if (scrollHeight - scrollTop <= offsetHeight * 2) {
        this.$refs["chat-room"].scrollTop = scrollHeight
      }
      if (this.first) {
        this.$refs["chat-room"].scrollTop = scrollHeight
        this.first = false
      }
    },
  },
  created() {
    this.initSocket()
    this.getHistory()
  },
  async mounted() {},
  methods: {
    handleBackIconClick() {
      this.$router.go(-1)
    },
    postMsg() {
      if (!this.currentMsg) return
      this.sendMsg()
      const msgAndUser = {
        msg: this.currentMsg,
        isSelf: true,
      }
      this.msgAndUsers.push(msgAndUser)

      this.currentMsg = ""
    },
    sendMsg() {
      this.socket.emit("chatMsg", {
        msg: this.currentMsg,
        senderId: this.$global.state.userId,
        receiverId: this.receiverId,
      })
    },
    initSocket() {
      const socket = io("http://sedationh.cn:3001")
      socket.on(
        this.$global.state.userId,
        ({ msg, senderId }) => {
          if (senderId !== this.receiverId) return
          this.msgAndUsers.push({
            msg,
            isSelf: false,
          })
        }
      )
      this.socket = socket
    },
    async getHistory() {
      const { selfMsg, otherMsg } = await this.$axios.get(
        "/msg",
        {
          params: {
            senderId: this.$global.state.userId,
            receiverId: this.receiverId,
          },
        }
      )

      const unSortedArray = [
        ...selfMsg.map(({ msg, createdAt }) => ({
          msg,
          createdAt,
          isSelf: true,
        })),
        ...otherMsg.map(({ msg, createdAt }) => ({
          msg,
          createdAt,
          isSelf: false,
        })),
      ]
      unSortedArray.sort(
        (a, b) =>
          new Date(a.createdAt) - new Date(b.createdAt)
      )
      this.msgAndUsers.push(...unSortedArray)
    },
  },
}
</script>

<style lang="scss" scoped>
// fix float invoke chat room lost height
// https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Overflowing_content#overflow_establishes_a_block_formatting_context
// create BFC
.chat-room {
  overflow: auto;
  height: calc(100vh - 70px - 54px);
}

.msg-action {
  background-color: #f2f2f2;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 4px;

  .icon-smile,
  .icon-voice {
    height: 25px;
    width: 25px;
    border: 1px solid black;
    border-radius: 50%;
    text-align: center;
    line-height: 27px;
  }

  input {
    border: none;
    width: 220px;
    height: 39px;
    border-radius: 3px;
    display: block;
    transition: all 0.3s;
    padding-left: 12px;
  }
}

.weui-btn_mini {
  margin: 0;
}
</style>
